from flask import Flask, render_template, request, redirect, url_for
import os
from utils import load_data, save_data, export_to_csv

app = Flask(__name__)

# 数据目录路径
data_dir = os.path.join(os.path.dirname(__file__), 'data')

# ------------------------ 首页 ------------------------
@app.route('/')
def dashboard():
    return render_template('dashboard.html')

# ------------------------ 客户管理 ------------------------
@app.route('/customers')
def customers():
    customers = load_data(os.path.join(data_dir, 'customers.json'))
    return render_template('customers.html', customers=customers)

@app.route('/customers/add', methods=['GET', 'POST'])
def add_customer():
    if request.method == 'POST':
        new_customer = {
            "customerID": request.form['customerID'],
            "customerName": request.form['customerName'],
            "PID": request.form['PID'],
            "telephone": request.form['telephone'],
            "address": request.form['address']
        }
        customers = load_data(os.path.join(data_dir, 'customers.json'))
        customers.append(new_customer)
        save_data(os.path.join(data_dir, 'customers.json'), customers)
        return redirect(url_for('customers'))
    return render_template('add_customer.html', customer=None)

@app.route('/customers/edit/<id>', methods=['GET', 'POST'])
def edit_customer(id):
    customers = load_data(os.path.join(data_dir, 'customers.json'))
    customer = next((c for c in customers if c['customerID'] == id), None)
    if not customer:
        return '客户不存在', 404
    if request.method == 'POST':
        customer['customerName'] = request.form['customerName']
        customer['PID'] = request.form['PID']
        customer['telephone'] = request.form['telephone']
        customer['address'] = request.form['address']
        save_data(os.path.join(data_dir, 'customers.json'), customers)
        return redirect(url_for('customers'))
    return render_template('edit_customer.html', customer=customer)

@app.route('/customers/delete/<id>')
def delete_customer(id):
    customers = load_data(os.path.join(data_dir, 'customers.json'))
    customers = [c for c in customers if c['customerID'] != id]
    save_data(os.path.join(data_dir, 'customers.json'), customers)
    return redirect(url_for('customers'))

@app.route('/customers/export')
def export_customers():
    customers = load_data(os.path.join(data_dir, 'customers.json'))
    export_to_csv(customers, ['customerID', 'customerName', 'PID', 'telephone', 'address'],
                  os.path.join(data_dir, 'customers_export.csv'))
    return redirect(url_for('customers'))

# ------------------------ 银行卡管理 ------------------------
@app.route('/cards')
def cards():
    cards = load_data(os.path.join(data_dir, 'cards.json'))
    return render_template('cards.html', cards=cards)

@app.route('/cards/add', methods=['GET', 'POST'])
def add_card():
    if request.method == 'POST':
        new_card = {
            "cardID": request.form['cardID'],
            "type": request.form['type'],
            "openDate": request.form['openDate'],
            "initAmount": float(request.form['initAmount']),
            "balance": float(request.form['balance']),
            "password": request.form['password'],
            "lost": request.form.get('lost') == 'on',
            "customerID": request.form['customerID']
        }
        cards = load_data(os.path.join(data_dir, 'cards.json'))
        if isinstance(cards, dict): cards = []  # 空文件处理
        cards.append(new_card)
        save_data(os.path.join(data_dir, 'cards.json'), cards)
        return redirect(url_for('cards'))
    customers = load_data(os.path.join(data_dir, 'customers.json'))  # 供选择客户编号
    return render_template('add_card.html', customers=customers, card=None)

@app.route('/cards/edit/<cardID>', methods=['GET', 'POST'])
def edit_card(cardID):
    cards = load_data(os.path.join(data_dir, 'cards.json'))
    card = next((c for c in cards if c['cardID'] == cardID), None)
    if not card:
        return '卡片不存在', 404
    if request.method == 'POST':
        card['type'] = request.form['type']
        card['openDate'] = request.form['openDate']
        card['initAmount'] = float(request.form['initAmount'])
        card['balance'] = float(request.form['balance'])
        card['password'] = request.form['password']
        card['lost'] = request.form.get('lost') == 'on'
        card['customerID'] = request.form['customerID']
        save_data(os.path.join(data_dir, 'cards.json'), cards)
        return redirect(url_for('cards'))
    customers = load_data(os.path.join(data_dir, 'customers.json'))
    return render_template('edit_card.html', card=card, customers=customers)

@app.route('/cards/delete/<cardID>')
def delete_card(cardID):
    cards = load_data(os.path.join(data_dir, 'cards.json'))
    cards = [c for c in cards if c['cardID'] != cardID]
    save_data(os.path.join(data_dir, 'cards.json'), cards)
    return redirect(url_for('cards'))

@app.route('/cards/export')
def export_cards():
    cards = load_data(os.path.join(data_dir, 'cards.json'))
    export_to_csv(cards, ['cardID', 'type', 'openDate', 'initAmount', 'balance', 'password', 'lost', 'customerID'],
                  os.path.join(data_dir, 'cards_export.csv'))
    return redirect(url_for('cards'))

# ------------------------ 运行应用 ------------------------
if __name__ == '__main__':
    app.run(debug=True)
